# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,time
from piHAlibs import (confgetval,coroutine,lst2lines)

logger = logging.getLogger()


def actionscriptexe(lines,Cmds):
    for ln in lines:
        cmd = ln.split()
        if len(cmd) < 2 : continue
        if cmd[0] in Cmds:
            Cmds[cmd[0]](cmd[1:])
            logger.debug("Execution of %s with args %s",repr(Cmds[cmd[0]]),repr(cmd[1:]))
            time.sleep(1)
        else:
            logger.debug("No execution with %s",repr(cmd))
            continue
    return


def startscriptexe(dev,lines):
    for ln in lines:
        if 'PAUSE' in ln:
            t = int(ln.split()[1])
            logger.debug("Script execution PAUSE for %s seconds",t)
            time.sleep(t)
        else:
            dev.write(ln)
            dev.flush()
            time.sleep(1)


@coroutine
def sysevents(Cmds):
    while True:
        line = (yield)
        item = line.split()
        if len(item) == 0:
            continue
        if item[0] in Cmds:
            if len(item) == 1:
                Cmds[item[0]]()
            else:
                Cmds[item[0]](item[1:])
        else:
            logger.error('Command %s unknown',item[0])
